package other.edan.erp.k3;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestBeanParam;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.XoqlService;
import org.apache.commons.lang.StringUtils;
import other.edan.erp.utils.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: 黎炎松
 * @Date: 2024/11/5 11:12
 */
@RestApi(baseUrl = "/edan/k3")
public class K3ClientApi extends SyncSuper {
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private XoqlService xoqlService = XoqlService.instance();

    public static void main(String[] args) {
        HCXObjectService.isLocal = true;
        K3ClientApi k3ClientApi = new K3ClientApi();
        //k3ClientApi.addUpInstallInfo("[{\"installationTime\":\"2024-11-19 02:43:00.0\",\"hospitalGrade\":\"二甲\",\"nameOfHospital\":\"桂林市阳朔县人民医院\"," +
        //        "\"snCode\":\"360873-M24518870010\",\"city\":\"桂林市\",\"dateOfDelivery\":\"2024-05-31 00:00:00.0\",\"telephone\":\"18076788430\",\"office\":\"南宁办\"," +
        //        "\"specifications\":\"EDAN，中性开机LOGO，中文，新DE12，9G45平台（SE-1201民营型号）\",\"productName\":\"83.61.360873\",\"submissionTime\":\"2024-11-19 09:05:23.0\"," +
        //        "\"edanId\":\"1d0c2440-ea1d-4e08-b61d-8bd1d42d3712\",\"natureOfHospital\":\"Government Hospital\",\"installer\":\"苏广平\",\"province\":\"广西壮族自治区\"," +
        //        "\"hospitalLevel\":\"Normal\",\"dealer\":\"广西宇洋科技有限公司\",\"productSeries\":\"心电整机\",\"workOrderNo\":\"AZ-20241118009\",\"contacts\":\"石青\"," +
        //        "\"hospitalDepartment\":\"ICU\"},{\"installationTime\":\"2024-11-19 16:30:00.0\",\"hospitalGrade\":\"其他\",\"nameOfHospital\":\"包头市固阳县中蒙医院\"," +
        //        "\"snCode\":\"360464-M24501510001\",\"city\":\"包头市\",\"dateOfDelivery\":\"2024-05-27 00:00:00.0\",\"telephone\":\"15598315551\",\"office\":\"内蒙联络处\"," +
        //        "\"specifications\":\"EDAN\",\"productName\":\"83.61.360464\",\"submissionTime\":\"2024-11-19 10:06:40.0\",\"edanId\":\"7c0cc68e-49e5-44e3-a7e0-1d2507fc9115\"," +
        //        "\"natureOfHospital\":\"Government Hospital\",\"installer\":\"王晓乾\",\"province\":\"内蒙古自治区\",\"hospitalLevel\":\"Normal\",\"dealer\":\"内蒙古锐强医疗器械有限责任公司\"," +
        //        "\"productSeries\":\"心电整机\",\"workOrderNo\":\"AZ-20241119010\",\"contacts\":\"张主任\",\"hospitalDepartment\":\"急诊科\"}]");


        //k3ClientApi.addUpCloudPlat("[{\"hospitalGrade\":\"二乙\",\"snCode\":\"M21900200009\",\"province\":\"云南\",\"city\":\"楚雄彝族自治州\",\"office\":\"昆明办\"," +
        //        "\"dateList\":[{\"date\":\"2024-11-21\",\"quantity\":21,\"cardType\":\"BG10\"}],\"hospital\":\"元谋县人民医院\",\"department\":\"ICU\",\"edanId\":\"1490916\"}," +
        //        "{\"hospitalGrade\":\"三甲\",\"snCode\":\"M21900200011\",\"province\":\"云南\",\"city\":\"昆明\",\"office\":\"昆明办\",\"dateList\":[{\"date\":\"2024-11-21\",\"quantity\":1,\"cardType\":\"BG3\"}]," +
        //        "\"hospital\":\"昆明市妇幼保健院呈贡院区\",\"department\":\"检验科\",\"edanId\":\"1490917\"},{\"hospitalGrade\":\"二甲\",\"snCode\":\"M21900280003\",\"province\":\"安徽\",\"city\":\"铜陵\",\"dateList\":[{\"date\":\"2024-11-21\"," +
        //        "\"quantity\":1,\"cardType\":\"BG10\"}],\"hospital\":\"安徽省铜陵市第二人民医院（东院）\",\"department\":\"其他科室\",\"edanId\":\"1490918\"}]");

        k3ClientApi.addUpEarnestMoney("[{\"fID\":\"1951\",\"fDatagramNo\":\"3\",\"fRecdate\":\"2024-07-11 00:00:00.0\",\"dept\":\"新疆办-POCT\",\"fPaymentNote\":\"\",\"fAllAmount\":\"29000.0000000000\",\"paybank\":\"新时代招行\",\"payor\":\"新疆盛和同创生物科技有限公司\",\"fAssistant\":\"张小信\",\"entryList\":[{\"fID\":\"1951\",\"fspmoney2\":\"20000.0000000000\",\"fBillNo_SRC1\":\"SEORD331761\",\"fkh\":\"东莞市汉和医疗器械有限公司\",\"fEntryID\":\"285\",\"fCountry\":\"深赣闽\",\"fNote2\":\"\",\"fText10\":\"202407812\",\"fAamout2\":\"9000.0000000000\",\"fRKamout2\":\"9000.0000000000\",\"fText6\":\"深圳办\"}],\"fRecamount2\":\"29000.0000000000\",\"fNote\":\"\",\"fbillNo\":\"00000855\"},{\"fID\":\"1958\",\"fDatagramNo\":\"10\",\"fRecdate\":\"2024-07-12 00:00:00.0\",\"dept\":\"兰州办\",\"fPaymentNote\":\"\",\"fAllAmount\":\"10200.0000000000\",\"paybank\":\"新时代招行\",\"payor\":\"甘肃智高云科贸有限公司\",\"fAssistant\":\"贾艳玲\",\"fBillerID\":\"贾艳玲\",\"entryList\":[{\"fID\":\"1958\",\"fspmoney2\":\"0E-10\",\"fBillNo_SRC1\":\"SEORD326394\",\"fkh\":\"甘肃智高云科贸有限公司\",\"fEntryID\":\"266\",\"fCountry\":\"直管区\",\"fNote2\":\"\",\"fText10\":\"202409017、202409018\",\"fKXLB\":\"01\",\"fAamout2\":\"9000.0000000000\",\"fRKamout2\":\"9000.0000000000\",\"fText6\":\"兰州办\"},{\"fID\":\"1958\",\"fspmoney2\":\"0E-10\",\"fBillNo_SRC1\":\"SEORD326335\",\"fkh\":\"甘肃智高云科贸有限公司\",\"fEntryID\":\"267\",\"fCountry\":\"直管区\",\"fNote2\":\"\",\"fText10\":\"202409014\",\"fKXLB\":\"01\",\"fAamout2\":\"1200.0000000000\",\"fRKamout2\":\"1200.0000000000\",\"fText6\":\"兰州办\"}],\"fRecamount2\":\"10200.0000000000\",\"fNote\":\"\",\"fbillNo\":\"00000862\"},{\"fID\":\"1960\",\"fDatagramNo\":\"12\",\"fRecdate\":\"2024-07-12 00:00:00.0\",\"dept\":\"兰州办\",\"fPaymentNote\":\"\",\"fAllAmount\":\"11000.0000000000\",\"paybank\":\"新时代招行\",\"payor\":\"甘肃智高云科贸有限公司\",\"fAssistant\":\"贾艳玲\",\"entryList\":[{\"fID\":\"1960\",\"fspmoney2\":\"0E-10\",\"fBillNo_SRC1\":\"SEORD326494\",\"fkh\":\"甘肃智高云科贸有限公司\",\"fEntryID\":\"269\",\"fCountry\":\"直管区\",\"fNote2\":\"\",\"fText10\":\"202411321、202411322\",\"fKXLB\":\"01\",\"fAamout2\":\"26000.0000000000\",\"fRKamout2\":\"11000.0000000000\",\"fText6\":\"兰州办\"}],\"fRecamount2\":\"11000.0000000000\",\"fNote\":\"\",\"fbillNo\":\"00000864\"}]");

    }

    /**
     * 回写订单模块数据
     * @param upData
     * @return
     */
    @RestMapping(value = "/upOrder", method = RequestMethod.POST)
    public ResultVo upOrder(@RestBeanParam(name = "body") String upData) {
        String MSG = "修改订单数据 ==> ";
        try {
            LOGGER.info(MSG + "处理开始: "+ upData);
            if (StringUtils.isBlank(upData)) {
                return ResultVo.error("传入参数不可为空");
            }

            JSONObject upOrderData = JSONObject.parseObject(upData);
            LOGGER.info(MSG + "upOrderData: "+ upOrderData);
            String billno = upOrderData.getString("billno");
            if (upOrderData.size() <= 1 || StringUtils.isBlank(billno)) {
                LOGGER.error(MSG + "传入参数异常");
                return ResultVo.error("传入参数异常");
            }

            // 获取订单
            String sql = String.format("select id from _order where po = '%s'", billno);
            Order upOrder = HCXObjectService.queryOne(sql);
            if (upOrder == null) {
                LOGGER.error(MSG + "订单编号异常");
                return ResultVo.error("订单编号异常");
            }

            // 更新字段
            String paymentDate = upOrderData.getString("paymentDate"); // 回款日期
            Double paymentAmount = upOrderData.getDouble("paymentAmount"); // 回款金额
            Double paymentTotalAmount = upOrderData.getDouble("paymentTotalAmount"); // 回款总金额
            String returnSalesMemo = upOrderData.getString("returnSalesMemo"); // 退货通知单
            String returnOrderNo = upOrderData.getString("returnOrderNo"); // 退货单编号
            String invoiceNumber = upOrderData.getString("invoiceNumber"); // 财务发票号码

            if (paymentDate != null) upOrder.setFHeadSelfS0174__c(DateTools.stringToLong(paymentDate, DateTools.FORMATTIME));
            if (paymentAmount != null) upOrder.setFHeadSelfS0177__c(paymentAmount);
            if (paymentTotalAmount != null) upOrder.setFHeadSelfS0199__c(paymentTotalAmount);
            if (returnSalesMemo != null) upOrder.setReturnNotice__c(returnSalesMemo);
            if (invoiceNumber != null) upOrder.setCaiWuFaPiaoNum__c(invoiceNumber);

            // 退货单编号
            upOrder.setRoStatus(1);
            if (returnOrderNo != null) {
                upOrder.setRo(returnOrderNo);
                upOrder.setRoStatus(2);
            }

            HCXObjectService.update(upOrder);
            LOGGER.info(MSG + "修改订单成功");
            return ResultVo.success("修改订单成功");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(MSG + "处理异常:" + e.getMessage());
            return ResultVo.error("处理异常:" + e.getMessage());
        }
    }

    /**
     * 新增、修改装机信息
     * @param installData
     * @return
     */
    @RestMapping(value = "/addUpInstallInfo", method = RequestMethod.POST)
    public ResultVo addUpInstallInfo(@RestBeanParam(name = "body") String installData) {
        String MSG = "新增、修改装机信息 ==> ";
        try {
            LOGGER.info(MSG + "处理开始: "+ installData);
            if (StringUtils.isBlank(installData)) {
                return ResultVo.error("传入参数不可为空");
            }
            List<JSONObject> installList = JSONArray.parseArray(installData, JSONObject.class);
            LOGGER.info(MSG + "installList: "+ installList.size());
            if (installList.size() > 100) {
                return ResultVo.error("单次处理数量不可大于100");
            }

            // 获取选项集
            JSONObject installDesc = ComUtils.getEntityDesc("installationInfo__c");

            Map<String, String> natureOpt = ComUtils.getMapsFromDescribeJson(installDesc, "natureOfHospital__c", "apiKey", "value"); // 医院性质
            Map<String, String> levelOpt = ComUtils.getMapsFromDescribeJson(installDesc, "hospitalLevel__c", "apiKey", "value"); // 医院级别
            Map<String, String> gradeOpt = ComUtils.getMapsFromDescribeJson(installDesc, "hospitalGrade__c", "label", "value"); // 医院等级
            Map<String, String> departOpt = ComUtils.getMapsFromDescribeJson(installDesc, "hospitalDepartment__c", "label", "value"); // 医院科室

            // 查询CRM系统中的数据
            String edanIds = installList.stream().map(v -> "'" + v.getString("edanId") + "'").collect(Collectors.joining(","));
            String sql = String.format("select id,edanId__c from installationInfo__c where edanId__c in (%s)", edanIds);
            Map<String, Long> crmInstallMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("edanId__c"), e2 -> e2.getLong("id"), (e, e1) -> e));
            LOGGER.info(MSG + "crmInstallMap: "+ crmInstallMap.size());

            // 产品
            Map<String, Long> crmProductMap = getCrmDataMap("product", "productName", installList);

            // SN码
            Map<String, Long> crmSnCodeMap = getCrmDataMap("snCode", "snCode", installList);

            // 获取装机用户
            Map<String, Long> crmUserMap = getCrmDataMap("user", "installer", installList);

            // 保存数据
            Map<String, ShippingPersonnelSheet__c> detailMap = new HashMap<>();
            List<InstallationInfo__c> crmAddList =new ArrayList<>();
            List<InstallationInfo__c> crmUpList =new ArrayList<>();
            for (JSONObject install : installList) {
                // 前置判断
                String edanId = install.getString("edanId");
                if (edanId == null) {
                    continue;
                }

                // 处理参数
                InstallationInfo__c installInfo = new InstallationInfo__c();

                // 编号
                String number = install.getString("number");
                if (number != null) {
                    installInfo.setName(number);
                }
                installInfo.setProvinces__c(install.getString("province")); // 省
                installInfo.setCitys__c(install.getString("city")); // 城市
                installInfo.setNameOfHospitals__c(install.getString("nameOfHospital")); // 医院名称
                installInfo.setHospitalGrade__c(getIntVal(gradeOpt.get(install.getString("hospitalGrade")))); // 医院等级
                installInfo.setHospitalLevel__c(getIntVal(levelOpt.get(install.getString("hospitalLevel")))); // 医院级别
                installInfo.setNatureOfHospital__c(getIntVal(natureOpt.get(install.getString("natureOfHospital")))); // 医院性质
                installInfo.setHospitalDepartment__c(getIntVal(departOpt.get(install.getString("hospitalDepartment")))); // 医院科室
                installInfo.setContacts__c(install.getString("contacts")); // 医院保修卡联系人
                installInfo.setWorkOrderNo__c(install.getString("workOrderNo")); // 工单号
                installInfo.setTelephone__c(install.getString("telephone")); // 保修卡联系人电话
                installInfo.setInstallationTime__c(getDateVal(install.getString("installationTime"), 2)); // 装机时间
                installInfo.setProductName__c(crmProductMap.get(install.getString("productName"))); // 产品名称
                installInfo.setSnCode__c(crmSnCodeMap.get(install.getString("snCode"))); // 产品序列号
                installInfo.setProductSeries__c(install.getString("productSeries")); // 产品系列
                installInfo.setSpecifications__c(install.getString("specifications")); // 规格型号
                installInfo.setDateOfDelivery__c(getDateVal(install.getString("dateOfDelivery"), 2)); // 出库日期
                installInfo.setDealers__c(install.getString("dealer")); // 经销商
                installInfo.setOffice__c(install.getString("office")); // 办事处
                installInfo.setSubmissionTime__c(getDateVal(install.getString("submissionTime"), 2)); // 提交时间

                // 装机人
                String installer = install.getString("installer");
                installInfo.setInstaller__c(installer);
                installInfo.setActualInstaller__c(crmUserMap.get(installer));

                if (crmInstallMap.containsKey(edanId)) {
                    // 修改
                    installInfo.setId(crmInstallMap.get(edanId));
                    crmUpList.add(installInfo);
                } else {
                    // 新增
                    installInfo.setEdanId__c(install.getString("edanId"));
                    installInfo.setEntityType(3533392362297960L);
                    crmAddList.add(installInfo);

                    // 考虑新增装机人明细
                    if (crmUserMap.containsKey(installer)) {
                        ShippingPersonnelSheet__c addSheet = new ShippingPersonnelSheet__c();
                        addSheet.setEntityType(3590014698429035L);
                        addSheet.setCustomItem25__c(crmUserMap.get(installer));
                        detailMap.put(edanId, addSheet);
                    }
                }

                // 保存
                if (crmAddList.size() > 50) {
                    BatchOperateResult batchOperateResult = HCXObjectService.insertBatch(crmAddList);
                    Boolean success = batchOperateResult.getSuccess();
                    if (!success) {
                        return ResultVo.error("批量新增异常:" + batchOperateResult.getErrorMessage());
                    }
                    crmAddList.clear();
                }
                if (crmUpList.size() > 50) {
                    BatchOperateResult batchOperateResult = HCXObjectService.updateBatch(crmUpList);
                    Boolean success = batchOperateResult.getSuccess();
                    if (!success) {
                        return ResultVo.error("批量修改异常:" + batchOperateResult.getErrorMessage());
                    }
                    crmUpList.clear();
                }
            }

            LOGGER.info(MSG + "crmAddList: "+ crmAddList.size());
            LOGGER.info(MSG + "crmUpList: "+ crmUpList.size());
            HCXObjectService.insertBatch(crmAddList);
            HCXObjectService.updateBatch(crmUpList);


            // 统一处理装机人明细
            if (detailMap.size() > 0) {

                // 再次查询主表的id
                Set<String> installSet = detailMap.keySet();
                LOGGER.info(MSG + "开始处理装机明细");
                edanIds = installSet.stream().map(v -> "'" + v + "'").collect(Collectors.joining(","));
                sql = String.format("select id,edanId__c from installationInfo__c where edanId__c in (%s)", edanIds);
                crmInstallMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("edanId__c"), e2 -> e2.getLong("id"), (e, e1) -> e));
                LOGGER.info(MSG + "crmInstallMap: "+ crmInstallMap.size());

                // 处理明细
                List<ShippingPersonnelSheet__c> crmAddDetailList =new ArrayList<>();
                for (String edanId : installSet) {
                    if (!crmInstallMap.containsKey(edanId)) {
                        continue;
                    }

                    Long masterId = crmInstallMap.get(edanId);
                    ShippingPersonnelSheet__c addSheet = detailMap.get(edanId);
                    addSheet.setInstallationInfo__c(masterId);
                    crmAddDetailList.add(addSheet);
                    if (crmAddDetailList.size() > 50) {
                        HCXObjectService.insertBatch(crmAddDetailList);
                        crmAddDetailList.clear();
                    }
                }
                HCXObjectService.insertBatch(crmAddDetailList);
                LOGGER.info(MSG + "处理装机明细完成");
            }

            LOGGER.info(MSG + "处理成功");

            return ResultVo.success("处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(MSG + "处理异常:" + e.getMessage());
            return ResultVo.error("处理异常:" + e.getMessage());
        }
    }


    /**
     * 新增、修改云平台运营数据
     * @param platData
     * @return
     */
    @RestMapping(value = "/addUpCloudPlat", method = RequestMethod.POST)
    public ResultVo addUpCloudPlat(@RestBeanParam(name = "body") String platData) {
        String MSG = "新增、修改云平台运营数据 ==> ";
        Map<String, List<JSONObject>> detailMap = new HashMap<>();
        try {
            LOGGER.info(MSG + "处理开始: "+ platData);
            if (StringUtils.isBlank(platData)) {
                return ResultVo.error("传入参数不可为空");
            }
            List<JSONObject> platList = JSONArray.parseArray(platData, JSONObject.class);
            LOGGER.info(MSG + "platData: "+ platList.size());
            if (platList.size() > 100) {
                return ResultVo.error("单次处理数量不可大于100");
            }

            // 获取系统中的云平台数据
            String edanIds = platList.stream().map(v -> "'" + v.getString("edanId") + "'").collect(Collectors.joining(","));
            String sql = String.format("select id,edanId__c from cloudPlatform__c where edanId__c in (%s)", edanIds);
            Map<String, Long> crmPlatMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("edanId__c"), e2 -> e2.getLong("id"), (e, e1) -> e));
            LOGGER.info(MSG + "crmPlatMap: "+ crmPlatMap.size());

            // 处理主表
            List<CloudPlatform__c> crmAddList = new ArrayList<>();
            List<CloudPlatform__c> crmUpList = new ArrayList<>();
            for (JSONObject plat : platList) {
                CloudPlatform__c cloudPlatform = new CloudPlatform__c();

                String edanId = plat.getString("edanId");
                cloudPlatform.setEdanId__c(edanId);

                String snCode = plat.getString("snCode");
                cloudPlatform.setSnCodes__c(snCode);

                cloudPlatform.setOffice__c(plat.getString("office"));
                cloudPlatform.setProvinces__c(plat.getString("province"));
                cloudPlatform.setCitys__c(plat.getString("city"));
                cloudPlatform.setHospitalName__c(plat.getString("hospital"));
                cloudPlatform.setHospitalGrade__c(plat.getString("hospitalGrade"));
                cloudPlatform.setDepartment__c(plat.getString("department"));

                // 判断主表是否已经存在
                if (crmPlatMap.containsKey(edanId)) {
                    cloudPlatform.setId(crmPlatMap.get(edanId));
                    crmUpList.add(cloudPlatform);
                } else {
                    cloudPlatform.setEntityType(3538056243583565L);
                    crmAddList.add(cloudPlatform);

                    // 明细 （数据不考虑后续的修改，只新增）
                    List<JSONObject> dateList = JSONArray.parseArray(plat.getString("dateList"), JSONObject.class);
                    detailMap.put(edanId, dateList);
                }

                if (crmAddList.size() > 100) {
                    HCXObjectService.insertBatch(crmAddList);
                    crmAddList.clear();
                }
                if (crmUpList.size() > 100) {
                    HCXObjectService.updateBatch(crmUpList);
                    crmUpList.clear();
                }
            }
            HCXObjectService.insertBatch(crmAddList);
            HCXObjectService.updateBatch(crmUpList);

            Set<String> edanIdSet = detailMap.keySet();
            if (edanIdSet.size() <= 0) {
                LOGGER.info(MSG + "处理完成(无需要处理的明细)");
                return ResultVo.success();
            }

            // 再次查询主表的id
            edanIds = edanIdSet.stream().map(v -> "'" + v + "'").collect(Collectors.joining(","));
            sql = String.format("select id,edanId__c from cloudPlatform__c where edanId__c in (%s)", edanIds);
            crmPlatMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("edanId__c"), e2 -> e2.getLong("id"), (e, e1) -> e));
            LOGGER.info(MSG + "crmPlatMap: "+ crmPlatMap.size());

            // 处理明细
            Map<String, Integer> cardTypeMap = ComUtils.getGlobalPicksMap("globalPick144__c", "optionLabel"); //【卡类型】通用选项集
            List<CloudPlatformDetail__c> crmAddDetailList =new ArrayList<>();
            for (String edanId : edanIdSet) {
                if (!crmPlatMap.containsKey(edanId)) {
                    continue;
                }

                Long masterId = crmPlatMap.get(edanId);
                List<JSONObject> detailList = detailMap.get(edanId);
                for (JSONObject detail : detailList) {
                    CloudPlatformDetail__c cloudPlatformDetail = new CloudPlatformDetail__c();
                    cloudPlatformDetail.setEntityType(3567686385228374L);
                    cloudPlatformDetail.setCloudPlatform__c(masterId);
                    cloudPlatformDetail.setQuantity__c(detail.getLong("quantity"));
                    cloudPlatformDetail.setCardType__c(cardTypeMap.get(detail.getString("cardType")));
                    cloudPlatformDetail.setDate__c(HCDateUtils.stringToLong(detail.getString("date"), HCDateUtils.FORMAT));
                    crmAddDetailList.add(cloudPlatformDetail);
                }

                if (crmAddDetailList.size() > 100) {
                    HCXObjectService.insertBatch(crmAddDetailList);
                    crmAddDetailList.clear();
                }
            }
            HCXObjectService.insertBatch(crmAddDetailList);

            LOGGER.info(MSG + "处理完成");
            return ResultVo.success("处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            // todo
            if (detailMap.size() > 0) {
                LOGGER.error(MSG + "已新增的数据code: " + StringUtils.join(detailMap.keySet(), ","));
            }

            LOGGER.error(MSG + "处理异常:" + e.getMessage());
            return ResultVo.error("处理异常:" + e.getMessage());
        }
    }


    /**
     * 新增、修改保证金数据
     * @param platData
     * @return
     */
    @RestMapping(value = "/addUpEarnestMoney", method = RequestMethod.POST)
    public ResultVo addUpEarnestMoney(@RestBeanParam(name = "body") String platData) {
        String MSG = "新增、修改保证金数据 ==> ";
        Map<String, List<JSONObject>> detailMap = new HashMap<>();
        try {
            LOGGER.info(MSG + "处理开始: "+ platData);
            if (StringUtils.isBlank(platData)) {
                return ResultVo.error("传入参数不可为空");
            }
            List<JSONObject> earnestList = JSONArray.parseArray(platData, JSONObject.class);
            LOGGER.info(MSG + "platData: "+ earnestList.size());
            if (earnestList.size() > 100) {
                return ResultVo.error("单次处理数量不可大于100");
            }

            // 统一获取K3数据
            Set<String> fbillNoSet = new HashSet<>();
            Set<String> userSet = new HashSet<>();
            Set<String> deptSet = new HashSet<>();
            for (JSONObject earnest : earnestList) {
                fbillNoSet.add("'" + earnest.getString("fbillNo") + "'");

                // 订单专员
                if (earnest.getString("fAssistant") != null)
                    userSet.add("'" + earnest.getString("fAssistant") + "'");

                // 认款人
                if (earnest.getString("fBillerID") != null)
                    userSet.add("'" + earnest.getString("fBillerID") + "'");

                // 部门
                String department = earnest.getString("dept");
                if (StringUtils.isNotBlank(department)) {
                    department = department.replace("-POCT", "");
                    deptSet.add("'" + department + "'");
                }
            }

            // 获取系统中的保证金数据
            String sql = String.format("select id,name from earnestMoney__c where name in (%s)", StringUtils.join(fbillNoSet, ","));
            Map<String, Long> crmEarnestMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("name"), e2 -> e2.getLong("id"), (e, e1) -> e));
            LOGGER.info(MSG + "crmEarnestMap: "+ crmEarnestMap.size());

            // 获取用户数据
            sql = String.format("select id,name from user where name in (%s)", StringUtils.join(userSet, ","));
            Map<String, Long> crmUserMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("name"), e2 -> e2.getLong("id"), (e, e1) -> e));
            LOGGER.info(MSG + "crmUserMap: "+ crmUserMap.size());

            // 获取系统中的部门
            sql = String.format("select id,departName from department where departName in (%s)", StringUtils.join(deptSet, ","));
            Map<String, Long> crmDepartMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getString("departName"), e1 -> e1.getLong("id"), (e, e1) -> e));


            // 处理主表
            Set<String> orderSet = new HashSet<>();
            List<EarnestMoney__c> crmAddList = new ArrayList<>();
            List<EarnestMoney__c> crmUpList = new ArrayList<>();
            for (JSONObject earnest : earnestList) {
                EarnestMoney__c earnestMoney = new EarnestMoney__c();
                earnestMoney.setFID__c(earnest.getString("fID"));
                earnestMoney.setFDatagramNo__c(earnest.getString("fDatagramNo")); // 报文编号
                //earnestMoney.setFDatagarmDate__c(getDateVal(earnest.getString("fRecdate"),2)); // 报文日期
                earnestMoney.setFRecdate__c(getDateVal(earnest.getString("fRecdate"),2)); // 到款日期
                earnestMoney.setFRecamount2__c(earnest.getDouble("fRecamount2")); // 到款金额
                earnestMoney.setFAssistant__c(crmUserMap.get(earnest.getString("fAssistant"))); // 订单专员
                //earnestMoney.setFAssistant__c(crmUserMap.get(earnest.getDouble("fAssistant"))); // 订单专员2
                earnestMoney.setPaybank__c(earnest.getString("paybank")); // 到款行
                earnestMoney.setPayor__c(earnest.getString("payor")); // 到款单位

                // 办事处/部门
                String department = earnest.getString("dept");
                if (StringUtils.isNotBlank(department)) {
                    department = department.replace("-POCT", "");
                    if (crmDepartMap.containsKey(department)) {
                        earnestMoney.setDept__c(crmDepartMap.get(department));
                    }
                }
                earnestMoney.setFBillerID__c(crmUserMap.get(earnest.getString("fBillerID"))); // 认款人
                earnestMoney.setFAllAmount__c(earnest.getDouble("fAllAmount")); // 金额
                earnestMoney.setFNote__c(earnest.getString("fNote")); // 备注
                earnestMoney.setFPaymentNote__c(earnest.getString("fPaymentNote")); // 摘要

                // 判断主表是否已经存在
                String fbillNo = earnest.getString("fbillNo");
                earnestMoney.setName(fbillNo);
                if (crmEarnestMap.containsKey(fbillNo)) {
                    earnestMoney.setId(crmEarnestMap.get(fbillNo));
                    crmUpList.add(earnestMoney);
                } else {
                    earnestMoney.setEntityType(3602989234723465L);
                    crmAddList.add(earnestMoney);

                    // 明细 （数据不考虑后续的修改，只新增）
                    List<JSONObject> entryList = JSONArray.parseArray(earnest.getString("entryList"), JSONObject.class);
                    // 获取明细里面的订单编号
                    for (JSONObject entry : entryList) {
                        if (entry.getString("fBillNo_SRC1") != null)
                            orderSet.add("'" + entry.getString("fBillNo_SRC1") + "'");
                    }
                    detailMap.put(fbillNo, entryList);
                }

                if (crmAddList.size() > 100) {
                    HCXObjectService.insertBatch(crmAddList);
                    crmAddList.clear();
                }
                if (crmUpList.size() > 100) {
                    HCXObjectService.updateBatch(crmUpList);
                    crmUpList.clear();
                }
            }
            HCXObjectService.insertBatch(crmAddList);
            HCXObjectService.updateBatch(crmUpList);

            Set<String> newFbillNoSet = detailMap.keySet();
            if (newFbillNoSet.size() <= 0) {
                LOGGER.info(MSG + "处理完成(无需要处理的明细)");
                return ResultVo.success();
            }

            // 再次查询主表的id
            String fbillNos = newFbillNoSet.stream().map(v -> "'" + v + "'").collect(Collectors.joining(","));
            sql = String.format("select id,name from earnestMoney__c where name in (%s)", fbillNos);
            crmEarnestMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("name"), e2 -> e2.getLong("id"), (e, e1) -> e));
            LOGGER.info(MSG + "crmEarnestMap: "+ crmEarnestMap.size());

            // 获取订单数据
            sql = String.format("select id,k3Billno__c from order where k3Billno__c in (%s)", StringUtils.join(orderSet, ","));
            Map<String, Long> crmOrderMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e1 -> e1.getString("k3Billno__c"), e2 -> e2.getLong("id"), (e, e1) -> e));
            LOGGER.info(MSG + "crmOrderMap: "+ crmOrderMap.size());

            // 处理明细
            Map<String, Integer> payTypeMap = ComUtils.getGlobalPicksMap("FKXLB__c", "optionApiKey"); //【款项类别】通用选项集
            List<EarnestMoneyEntry__c> crmAddDetailList =new ArrayList<>();
            for (String fbillNo : newFbillNoSet) {
                if (!crmEarnestMap.containsKey(fbillNo)) {
                    continue;
                }

                Long masterId = crmEarnestMap.get(fbillNo);
                List<JSONObject> detailList = detailMap.get(fbillNo);
                for (JSONObject detail : detailList) {
                    EarnestMoneyEntry__c earnestMoneyEntry = new EarnestMoneyEntry__c();
                    earnestMoneyEntry.setName(detail.getString("fEntryID"));
                    earnestMoneyEntry.setEntityType(3602982974364326L);
                    earnestMoneyEntry.setEarnestMoney__c(masterId);
                    earnestMoneyEntry.setFID__c(detail.getString("fID"));
                    earnestMoneyEntry.setFKXLB__c(payTypeMap.get(detail.getString("fKXLB"))); // 贷款类别
                    earnestMoneyEntry.setFBillNo_SRC1__c(detail.getString("fBillNo_SRC1")); // 订单号
                    earnestMoneyEntry.setRelationOrder__c(crmOrderMap.get(detail.getString("fBillNo_SRC1"))); // 订单
                    earnestMoneyEntry.setFText10__c(detail.getString("fText10")); // 合同号
                    earnestMoneyEntry.setFkh__c(detail.getString("fkh")); // 订单客户
                    earnestMoneyEntry.setFCountry__c(detail.getString("fCountry")); // 大区
                    earnestMoneyEntry.setFText6__c(detail.getString("fText6")); // 订单部门
                    earnestMoneyEntry.setFAamout2__c(detail.getDouble("fAamout2")); // 订单金额
                    earnestMoneyEntry.setFRKamout2__c(detail.getDouble("fRKamout2")); // 认款金额
                    earnestMoneyEntry.setFspmoney2__c(detail.getDouble("fspmoney2")); // 到款金额
                    earnestMoneyEntry.setFNote2__c(detail.getString("fNote2")); // 备注
                    crmAddDetailList.add(earnestMoneyEntry);
                }

                if (crmAddDetailList.size() > 100) {
                    HCXObjectService.insertBatch(crmAddDetailList);
                    crmAddDetailList.clear();
                }
            }
            HCXObjectService.insertBatch(crmAddDetailList);

            LOGGER.info(MSG + "处理完成");
            return ResultVo.success("处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            // todo
            if (detailMap.size() > 0) {
                LOGGER.error(MSG + "已新增的数据code: " + StringUtils.join(detailMap.keySet(), ","));
            }

            LOGGER.error(MSG + "处理异常:" + e.getMessage());
            return ResultVo.error("处理异常:" + e.getMessage());
        }
    }



}
